﻿using System;
using Avalonia.Controls;
using Avalonia.Controls.Notifications;
using Avalonia.Interactivity;
using iOSClub.App.Desktop.Views;

namespace iOSClub.App.Desktop.ToolPages.Encode;

public partial class Base64StringView : UserControl
{
    public Base64StringView()
    {
        InitializeComponent();
        EncryptBox = this.FindControl<TextBox>("EncryptBox");
        DecryptBox = this.FindControl<TextBox>("DecryptBox");
    }

    private void ClearEncryptClick(object? sender, RoutedEventArgs e)
    {
        EncryptBox.Text = "";
    }

    private void ClearDecryptClick(object? sender, RoutedEventArgs e)
    {
        DecryptBox.Text = "";
    }

    private void CopyEncryptClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(EncryptBox.Text))return;
        var main = ViewOpera.GetView<MainWindow>(this);
        main?.CopyContext(EncryptBox.Text,new Notification("复制成功","已将解码内容复制到剪切板"));
    }

    private void CopyDecryptClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(DecryptBox.Text))return;
        var main = ViewOpera.GetView<MainWindow>(this);
        main?.CopyContext(DecryptBox.Text,new Notification("复制成功","已将解码内容复制到剪切板"));
    }

    private void EncryptTextClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(EncryptBox.Text))return;
        var plainTextBytes = System.Text.Encoding.UTF8.GetBytes((string)EncryptBox.Text);
        DecryptBox.Text = Convert.ToBase64String(plainTextBytes);
    }

    private void DecryptTextClick(object? sender, RoutedEventArgs e)
    {
        if(string.IsNullOrEmpty(DecryptBox.Text))return;
        try
        {
            var base64EncodedBytes = Convert.FromBase64String(DecryptBox.Text);
            EncryptBox.Text = System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
        }
        catch
        {
            EncryptBox.Text = "";
        }
    }
}